//$Id:  $
//$Date:  $
//$Author:  $
package com.ajaxit.prisa.struts;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.ajaxit.prisa.daos.ModuloDAO;
import com.ajaxit.prisa.daos.PaginaDAO;
import com.ajaxit.prisa.daos.UsuarioDAO;
import com.ajaxit.prisa.values.ModuloVO;
import com.ajaxit.prisa.values.PaginaVO;
import com.ajaxit.prisa.values.UsuarioVO;

public class ValidarUsuarioAction extends Action {
	private static final long serialVersionUID = 1L;

	public ActionForward execute ( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception {
		ValidarUsuarioForm validarUsuarioForm = (ValidarUsuarioForm)form;
		UsuarioVO usuario = new UsuarioVO ( );
		usuario.setLogin ( validarUsuarioForm.getLogin ( ) );
		usuario.setPasswd ( validarUsuarioForm.getPasswd ( ) );
        HttpSession session = request.getSession ( );
        UsuarioVO logged = UsuarioDAO.getInstance ( ).validarUsuario ( usuario );
        if ( logged == null ) {
    		ActionErrors errors = new ActionErrors ( );
			errors.add ( "passwd", new ActionMessage ( "error.invalid.login" ) );
        	return sendError ( mapping, request, null );
        }
        Collection<ModuloVO> modulos = ModuloDAO.getInstance ( ).findByUsuario ( logged.getLogin ( ) );
        Iterator<ModuloVO> it = modulos.iterator ( );
        Collection<Collection<PaginaVO>> paginasModulo = new ArrayList<Collection<PaginaVO>>();
        while ( it.hasNext ( ) ) 
        	paginasModulo.add ( PaginaDAO.getInstance ( ).findByModulo ( it.next ( ).getId ( ) ) );
        session.setAttribute ( "user", logged );
        session.setAttribute ( "modulos", modulos );
        session.setAttribute ( "paginasModulo", paginasModulo );
		return mapping.findForward ( "success" );
	}

	private ActionForward sendError ( ActionMapping mapping, HttpServletRequest request, ActionMessages errors ) {
		saveErrors ( request, errors );
		return new ActionForward ( mapping.getInput ( ) );
	}
}
//$Revision:  $
